package com.pengchuang.ACS.admin.boot.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pengchuang.ACS.admin.api.dto.RolePermissionDTO;
import com.pengchuang.ACS.admin.boot.dao.SysPermissionMapper;
import com.pengchuang.ACS.admin.boot.dao.SysRolePermissionDao;
import com.pengchuang.ACS.admin.boot.entity.SysPermission;
import com.pengchuang.ACS.admin.boot.entity.SysRoleEntity;
import com.pengchuang.ACS.admin.boot.entity.SysRolePermissionEntity;
import com.pengchuang.ACS.admin.boot.service.ISysPermissionService;

import com.pengchuang.ACS.common.constant.GlobalConstants;
import com.pengchuang.ACS.common.utils.PageUtils;
import com.pengchuang.ACS.common.utils.Query;
import com.pengchuang.ACS.common.utils.R;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements ISysPermissionService {

    private final RedisTemplate redisTemplate;

    private final SysRolePermissionDao rolePermissionDao;

    @Override
    public boolean refreshPermRolesRules() {
        redisTemplate.delete(GlobalConstants.URL_PERM_ROLES_KEY);
        List<SysPermission> permissions = this.listPermRoles();
        if (CollectionUtil.isNotEmpty(permissions)) {
            // 初始化URL- 角色规则
            List<SysPermission> urlPermList = permissions.stream()
                    .filter(item -> StrUtil.isNotBlank(item.getUrlPerm()))
                    .collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(urlPermList)) {
                Map<String, List<String>> urlPermRoles = new HashMap<>();
                urlPermList.stream().forEach(item -> {
                    String perm = item.getUrlPerm();
                    List<String> roles = item.getRoles();
                    urlPermRoles.put(perm, roles);
                });
                redisTemplate.opsForHash().putAll(GlobalConstants.URL_PERM_ROLES_KEY, urlPermRoles);
            }
        }
        return true;
    }

    @Override
    public List<SysPermission> listPermRoles() {
        return this.baseMapper.listPermRoles();
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SysPermission> page = this.page(
                new Query<SysPermission>().getPage(params),
                new QueryWrapper<SysPermission>());

        for (SysPermission record : page.getRecords()) {
            List<SysRoleEntity> roles = new ArrayList<>();
            List<String> rolesName = new ArrayList<>();
            for (SysRoleEntity sysRoleEntity : this.baseMapper.getRolesByPermId(record.getId())) {
                roles.add(sysRoleEntity);
                rolesName.add(sysRoleEntity.getName());
            }

            record.setRoles(rolesName);
            record.setSysRoles(roles);
        }

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageWithWord(Map<String, Object> params) {
        IPage<SysPermission> page = this.page(
                new Query<SysPermission>().getPage(params),
                new QueryWrapper<SysPermission>().like("name", params.get("word")));
        return new PageUtils(page);
    }

    @Override
    public void saveWithRole(SysPermission sysPermission) {
        this.baseMapper.insert(sysPermission);
        for (String role : sysPermission.getRoles()) {
            rolePermissionDao.insert(SysRolePermissionEntity.builder()
                            .permissionId(sysPermission.getId()).roleId(Long.valueOf(role)).build());
        }
    }
}
